<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.9.0">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"way1989.github.io","root":"/","scheme":"Mist","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="Camera2录像流程">
<meta name="keywords" content="博客">
<meta property="og:type" content="article">
<meta property="og:title" content="Camera2录像流程">
<meta property="og:url" content="https://way1989.github.io/2017/01/18/blogs/Camera2/index.html">
<meta property="og:site_name" content="Broncho">
<meta property="og:description" content="Camera2录像流程">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2020-08-15T07:52:32.558Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Camera2录像流程">
<meta name="twitter:description" content="Camera2录像流程">

<link rel="canonical" href="https://way1989.github.io/2017/01/18/blogs/Camera2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Camera2录像流程 | Broncho</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Broncho</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/way1989" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://way1989.github.io/2017/01/18/blogs/Camera2/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="Broncho">
      <meta itemprop="description" content="爱生活...爱Android...">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Broncho">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Camera2录像流程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-01-18 16:00:24" itemprop="dateCreated datePublished" datetime="2017-01-18T16:00:24+08:00">2017-01-18</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-08-15 15:52:32" itemprop="dateModified" datetime="2020-08-15T15:52:32+08:00">2020-08-15</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/博客/" itemprop="url" rel="index"><span itemprop="name">博客</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/博客/Camera2/" itemprop="url" rel="index"><span itemprop="name">Camera2</span></a>
                </span>
            </span>

          
            <div class="post-description">Camera2录像流程</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h2 id="Android-M版本及以上需要申请权限"><a href="#Android-M版本及以上需要申请权限" class="headerlink" title="Android M版本及以上需要申请权限"></a>Android M版本及以上需要申请权限</h2><p> 申请<code>CAMERA</code>和<code>RECORD_AUDIO</code>权限。</p>
<h2 id="在TextureView可用的时候，打开Camera，通过CameraDevice-StateCallback回调获取打开结果。"><a href="#在TextureView可用的时候，打开Camera，通过CameraDevice-StateCallback回调获取打开结果。" class="headerlink" title="在TextureView可用的时候，打开Camera，通过CameraDevice.StateCallback回调获取打开结果。"></a>在TextureView可用的时候，打开Camera，通过<code>CameraDevice.StateCallback</code>回调获取打开结果。</h2><p> 其中openCamera函数声明如下（<code>cameraId</code>：Camera的id，通常0表示后置摄像头，1表示前置摄像头；<code>callback</code>: <code>CameraDevice.StateCallback</code>相机状态回调; <code>handler</code>:执行回调操作的hanlder，为空时，在主线程中执行，如果传入异步线程的handler,则在异步线程中执行）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RequiresPermission</span>(android.Manifest.permission.CAMERA)</span><br><span class="line">   <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">openCamera</span><span class="params">(@NonNull String cameraId,</span></span></span><br><span class="line"><span class="function"><span class="params">           @NonNull <span class="keyword">final</span> CameraDevice.StateCallback callback, @Nullable Handler handler)</span></span></span><br><span class="line"><span class="function">           <span class="keyword">throws</span> CameraAccessException </span>&#123;</span><br><span class="line">           &#125;</span><br></pre></td></tr></table></figure>
<p> 完整打开Camera代码如下:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Tries to open a &#123;<span class="doctag">@link</span> CameraDevice&#125;. The result is listened by `mStateCallback`.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">openCamera</span><span class="params">(<span class="keyword">int</span> width, <span class="keyword">int</span> height)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!hasPermissionsGranted(VIDEO_PERMISSIONS)) &#123;</span><br><span class="line">        requestVideoPermissions();</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">final</span> Activity activity = getActivity();</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == activity || activity.isFinishing()) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//获取CameraManager对象</span></span><br><span class="line">    CameraManager manager = (CameraManager) activity.getSystemService(Context.CAMERA_SERVICE);</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        Log.d(TAG, <span class="string">"tryAcquire"</span>);</span><br><span class="line">        <span class="comment">//做打开超时判断，超过2.5秒则抛出异常，对应release()结束</span></span><br><span class="line">        <span class="keyword">if</span> (!mCameraOpenCloseLock.tryAcquire(<span class="number">2500</span>, TimeUnit.MILLISECONDS)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Time out waiting to lock camera opening."</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        String cameraId = manager.getCameraIdList()[<span class="number">0</span>];<span class="comment">//获取后摄id</span></span><br><span class="line"></span><br><span class="line">        <span class="comment">// Choose the sizes for camera preview and video recording</span></span><br><span class="line">        CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraId);</span><br><span class="line">        <span class="comment">//类似之前的Parameters</span></span><br><span class="line">        StreamConfigurationMap map = characteristics</span><br><span class="line">                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);</span><br><span class="line">        mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);</span><br><span class="line">        <span class="comment">//选择录像尺寸</span></span><br><span class="line">        mVideoSize = chooseVideoSize(map.getOutputSizes(MediaRecorder.class));</span><br><span class="line">        <span class="comment">//选择合适的预览尺寸</span></span><br><span class="line">        mPreviewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture.class),</span><br><span class="line">                width, height, mVideoSize);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">int</span> orientation = getResources().getConfiguration().orientation;</span><br><span class="line">        <span class="keyword">if</span> (orientation == Configuration.ORIENTATION_LANDSCAPE) &#123;</span><br><span class="line">            mTextureView.setAspectRatio(mPreviewSize.getWidth(), mPreviewSize.getHeight());</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            mTextureView.setAspectRatio(mPreviewSize.getHeight(), mPreviewSize.getWidth());</span><br><span class="line">        &#125;</span><br><span class="line">        configureTransform(width, height);</span><br><span class="line">        mMediaRecorder = <span class="keyword">new</span> MediaRecorder();</span><br><span class="line">        <span class="comment">//打开Camera，通过CameraDevice.StateCallback回调打开结果</span></span><br><span class="line">        manager.openCamera(cameraId, mStateCallback, <span class="keyword">null</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CameraAccessException e) &#123;</span><br><span class="line">        Toast.makeText(activity, <span class="string">"Cannot access the camera."</span>, Toast.LENGTH_SHORT).show();</span><br><span class="line">        activity.finish();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (NullPointerException e) &#123;</span><br><span class="line">        <span class="comment">// Currently an NPE is thrown when the Camera2API is used but not supported on the</span></span><br><span class="line">        <span class="comment">// device this code runs.</span></span><br><span class="line">        ErrorDialog.newInstance(getString(R.string.camera_error))</span><br><span class="line">                .show(getChildFragmentManager(), FRAGMENT_DIALOG);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (InterruptedException e) &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> RuntimeException(<span class="string">"Interrupted while trying to lock camera opening."</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="调用openCamera方法后会回调CameraDevice-StateCallback这个接口，在该接口里重写onOpened函数，开启预览。"><a href="#调用openCamera方法后会回调CameraDevice-StateCallback这个接口，在该接口里重写onOpened函数，开启预览。" class="headerlink" title="调用openCamera方法后会回调CameraDevice.StateCallback这个接口，在该接口里重写onOpened函数，开启预览。"></a>调用<code>openCamera</code>方法后会回调<code>CameraDevice.StateCallback</code>这个接口，在该接口里重写<code>onOpened</code>函数，开启预览。</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * &#123;<span class="doctag">@link</span> CameraDevice.StateCallback&#125; is called when &#123;<span class="doctag">@link</span> CameraDevice&#125; changes its status.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">private</span> CameraDevice.StateCallback mStateCallback = <span class="keyword">new</span> CameraDevice.StateCallback() &#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onOpened</span><span class="params">(CameraDevice cameraDevice)</span> </span>&#123;<span class="comment">//打开Camera成功</span></span><br><span class="line">        mCameraDevice = cameraDevice;</span><br><span class="line">        startPreview();<span class="comment">//开始预览</span></span><br><span class="line">        mCameraOpenCloseLock.release();<span class="comment">//释放掉超时判断</span></span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != mTextureView) &#123;</span><br><span class="line">            configureTransform(mTextureView.getWidth(), mTextureView.getHeight());</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onDisconnected</span><span class="params">(CameraDevice cameraDevice)</span> </span>&#123;<span class="comment">//Camera断开连接</span></span><br><span class="line">        mCameraOpenCloseLock.release();</span><br><span class="line">        cameraDevice.close();</span><br><span class="line">        mCameraDevice = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onError</span><span class="params">(CameraDevice cameraDevice, <span class="keyword">int</span> error)</span> </span>&#123;<span class="comment">//打开Camera失败</span></span><br><span class="line">        mCameraOpenCloseLock.release();</span><br><span class="line">        cameraDevice.close();</span><br><span class="line">        mCameraDevice = <span class="keyword">null</span>;</span><br><span class="line">        Activity activity = getActivity();</span><br><span class="line">        <span class="keyword">if</span> (<span class="keyword">null</span> != activity) &#123;</span><br><span class="line">            activity.finish();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h2 id="开启预览主要就是使用CameraDevice来创建会话createCaptureSession。"><a href="#开启预览主要就是使用CameraDevice来创建会话createCaptureSession。" class="headerlink" title="开启预览主要就是使用CameraDevice来创建会话createCaptureSession。"></a>开启预览主要就是使用<code>CameraDevice</code>来创建会话<code>createCaptureSession</code>。</h2><p> 声明如下（<code>outputs</code>:预览输出载体，比如TextureView的getSurfaceTexture()，拍照时ImageReader的getSurface()，录像时MediaRecorder的getSurface()；<code>callback</code>:摄像头采集状态回调；<code>handler</code>:同openCamera）：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">abstract</span> <span class="keyword">void</span> <span class="title">createCaptureSession</span><span class="params">(@NonNull List&lt;Surface&gt; outputs,</span></span></span><br><span class="line"><span class="function"><span class="params">        @NonNull CameraCaptureSession.StateCallback callback, @Nullable Handler handler)</span></span></span><br><span class="line"><span class="function">        <span class="keyword">throws</span> CameraAccessException</span>;</span><br></pre></td></tr></table></figure>
<p>完整的startPreview函数如下：<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Start the camera preview.</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">startPreview</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == mCameraDevice || !mTextureView.isAvailable() || <span class="keyword">null</span> == mPreviewSize) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        closePreviewSession();</span><br><span class="line">        SurfaceTexture texture = mTextureView.getSurfaceTexture();<span class="comment">//获取TextureView的SurfaceTexture，作为预览输出载体</span></span><br><span class="line">        <span class="keyword">assert</span> texture != <span class="keyword">null</span>;</span><br><span class="line">        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());</span><br><span class="line">        <span class="comment">//创建CameraRequest.Builder, 当程序调用setRepeatingRequest()方法进行预览时，</span></span><br><span class="line">        <span class="comment">// 或调用capture()方法进行拍照时，都需要传入CameraRequest参数.</span></span><br><span class="line">        <span class="comment">// CameraRequest代表了一次捕获请求，用于描述捕获图片的各种参数设置，</span></span><br><span class="line">        <span class="comment">// 比如对焦模式、曝光模式……程序需要对照片所做的各种控制，都通过CameraRequest参数进行设置。</span></span><br><span class="line">        <span class="comment">// 可以理解一个请求参数一样，CameraRequest.Builder则负责生成CameraRequest对象。</span></span><br><span class="line">        mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);</span><br><span class="line"></span><br><span class="line">        Surface previewSurface = <span class="keyword">new</span> Surface(texture);</span><br><span class="line">        mPreviewBuilder.addTarget(previewSurface);</span><br><span class="line"></span><br><span class="line">        mCameraDevice.createCaptureSession(Arrays.asList(previewSurface), <span class="keyword">new</span> CameraCaptureSession.StateCallback() &#123;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onConfigured</span><span class="params">(CameraCaptureSession cameraCaptureSession)</span> </span>&#123;</span><br><span class="line">                    mPreviewSession = cameraCaptureSession;</span><br><span class="line">                    mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);</span><br><span class="line">                    <span class="comment">//不停的发送获取图像请求，完成连续预览</span></span><br><span class="line">                    mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), <span class="keyword">null</span>, mBackgroundHandler);</span><br><span class="line">                &#125;</span><br><span class="line"></span><br><span class="line">                <span class="meta">@Override</span></span><br><span class="line">                <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onConfigureFailed</span><span class="params">(CameraCaptureSession cameraCaptureSession)</span> </span>&#123;</span><br><span class="line">                    Activity activity = getActivity();</span><br><span class="line">                    <span class="keyword">if</span> (<span class="keyword">null</span> != activity) &#123;</span><br><span class="line">                        Toast.makeText(activity, <span class="string">"Failed"</span>, Toast.LENGTH_SHORT).show();</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;, mBackgroundHandler);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (CameraAccessException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></p>
<p> setRepeatingRequest和capture方法其实都是向相机设备发送获取图像的请求，但是capture就获取那么一次，而setRepeatingRequest就是不停的获取图像数据，所以呢，使用capture就像拍照一样，图像就停在那里，但是setRepeatingRequest一直在发送和获取，所以需要连拍的时候就调用它，然后在onCaptureCompleted中保存图像就行了。（注意了，图像的预览也是用的setRepeatingRequest，只是不处理数据）</p>
<h2 id="至此，Camera已经完成预览，等待用户输入开始录像事件。"><a href="#至此，Camera已经完成预览，等待用户输入开始录像事件。" class="headerlink" title="至此，Camera已经完成预览，等待用户输入开始录像事件。"></a>至此，Camera已经完成预览，等待用户输入开始录像事件。</h2><p>当用户点击录像按钮时，先配置好<code>MediaRecorder</code>相关参数，然后重启预览，并在预览开始时调用<code>MediaRecorder.start()</code>,正式开始录像：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">startRecordingVideo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> == mCameraDevice || !mTextureView.isAvailable() || <span class="keyword">null</span> == mPreviewSize) &#123;</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        closePreviewSession();<span class="comment">//先关闭预览，因为需要添加一个预览输入载体到MediaRecorder.getSurface()</span></span><br><span class="line">        setUpMediaRecorder();<span class="comment">//设置MediaRecorder相关参数</span></span><br><span class="line">        SurfaceTexture texture = mTextureView.getSurfaceTexture();<span class="comment">//获取TextureView的输出载体</span></span><br><span class="line">        <span class="keyword">assert</span> texture != <span class="keyword">null</span>;</span><br><span class="line">        texture.setDefaultBufferSize(mPreviewSize.getWidth(), mPreviewSize.getHeight());</span><br><span class="line">        <span class="comment">//准备创建CaptureRequest</span></span><br><span class="line">        mPreviewBuilder = mCameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);</span><br><span class="line">        List&lt;Surface&gt; surfaces = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Set up Surface for the camera preview</span></span><br><span class="line">        Surface previewSurface = <span class="keyword">new</span> Surface(texture);</span><br><span class="line">        surfaces.add(previewSurface);</span><br><span class="line">        mPreviewBuilder.addTarget(previewSurface);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Set up Surface for the MediaRecorder</span></span><br><span class="line">        mRecorderSurface = mMediaRecorder.getSurface();<span class="comment">//获取MediaRecorder预览输出载体</span></span><br><span class="line">        surfaces.add(mRecorderSurface);</span><br><span class="line">        mPreviewBuilder.addTarget(mRecorderSurface);</span><br><span class="line"></span><br><span class="line">        <span class="comment">// Start a capture session</span></span><br><span class="line">        <span class="comment">// Once the session starts, we can update the UI and start recording</span></span><br><span class="line">        mCameraDevice.createCaptureSession(surfaces, <span class="keyword">new</span> CameraCaptureSession.StateCallback() &#123;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onConfigured</span><span class="params">(@NonNull CameraCaptureSession cameraCaptureSession)</span> </span>&#123;</span><br><span class="line">                mPreviewSession = cameraCaptureSession;</span><br><span class="line">                mPreviewBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);</span><br><span class="line">                <span class="comment">//不停的发送获取图像请求，完成连续预览</span></span><br><span class="line">                mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), <span class="keyword">null</span>, mBackgroundHandler);</span><br><span class="line">                getActivity().runOnUiThread(<span class="keyword">new</span> Runnable() &#123;</span><br><span class="line">                    <span class="meta">@Override</span></span><br><span class="line">                    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">run</span><span class="params">()</span> </span>&#123;</span><br><span class="line">                        <span class="comment">// UI</span></span><br><span class="line">                        mButtonVideo.setText(R.string.stop);</span><br><span class="line">                        mIsRecordingVideo = <span class="keyword">true</span>;</span><br><span class="line"></span><br><span class="line">                        <span class="comment">// Start recording</span></span><br><span class="line">                        mMediaRecorder.start();<span class="comment">//正式开始录像</span></span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            <span class="meta">@Override</span></span><br><span class="line">            <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onConfigureFailed</span><span class="params">(@NonNull CameraCaptureSession cameraCaptureSession)</span> </span>&#123;</span><br><span class="line">                Activity activity = getActivity();</span><br><span class="line">                <span class="keyword">if</span> (<span class="keyword">null</span> != activity) &#123;</span><br><span class="line">                    Toast.makeText(activity, <span class="string">"Failed"</span>, Toast.LENGTH_SHORT).show();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;, mBackgroundHandler);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (CameraAccessException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源："><a href="#当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源：" class="headerlink" title="当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源："></a>当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源：</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">stopRecordingVideo</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="comment">// UI</span></span><br><span class="line">    mIsRecordingVideo = <span class="keyword">false</span>;</span><br><span class="line">    mButtonVideo.setText(R.string.record);</span><br><span class="line">    <span class="comment">// Stop recording</span></span><br><span class="line">    mMediaRecorder.stop();</span><br><span class="line">    mMediaRecorder.reset();</span><br><span class="line"></span><br><span class="line">    Activity activity = getActivity();</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">null</span> != activity) &#123;</span><br><span class="line">        Toast.makeText(activity, <span class="string">"Video saved: "</span> + mNextVideoAbsolutePath,</span><br><span class="line">                Toast.LENGTH_SHORT).show();</span><br><span class="line">        Log.d(TAG, <span class="string">"Video saved: "</span> + mNextVideoAbsolutePath);</span><br><span class="line">    &#125;</span><br><span class="line">    mNextVideoAbsolutePath = <span class="keyword">null</span>;</span><br><span class="line">    startPreview();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

    </div>

    
    
    
        <div class="reward-container">
  <div></div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/images/wechatpay.jpg" alt="Broncho 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/images/alipay.jpg" alt="Broncho 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/博客/" rel="tag"># 博客</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2017/01/16/blogs/RuntimeResourceOverlay/" rel="prev" title="Android运行时资源覆盖">
      <i class="fa fa-chevron-left"></i> Android运行时资源覆盖
    </a></div>
      <div class="post-nav-item">
    <a href="/2017/06/07/notes/AndroidLanguage/" rel="next" title="Android开发各国语言后缀对照">
      Android开发各国语言后缀对照 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    
  <div class="comments">
    <div id="lv-container" data-id="city" data-uid="MTAyMC8zNzk3MC8xNDUwMA=="></div>
  </div>
  

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Android-M版本及以上需要申请权限"><span class="nav-number">1.</span> <span class="nav-text">Android M版本及以上需要申请权限</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#在TextureView可用的时候，打开Camera，通过CameraDevice-StateCallback回调获取打开结果。"><span class="nav-number">2.</span> <span class="nav-text">在TextureView可用的时候，打开Camera，通过CameraDevice.StateCallback回调获取打开结果。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#调用openCamera方法后会回调CameraDevice-StateCallback这个接口，在该接口里重写onOpened函数，开启预览。"><span class="nav-number">3.</span> <span class="nav-text">调用openCamera方法后会回调CameraDevice.StateCallback这个接口，在该接口里重写onOpened函数，开启预览。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#开启预览主要就是使用CameraDevice来创建会话createCaptureSession。"><span class="nav-number">4.</span> <span class="nav-text">开启预览主要就是使用CameraDevice来创建会话createCaptureSession。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#至此，Camera已经完成预览，等待用户输入开始录像事件。"><span class="nav-number">5.</span> <span class="nav-text">至此，Camera已经完成预览，等待用户输入开始录像事件。</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源："><span class="nav-number">6.</span> <span class="nav-text">当用户再点击停止录像按钮时，就停止录像了，释放掉一些资源：</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Broncho"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">Broncho</p>
  <div class="site-description" itemprop="description">爱生活...爱Android...</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">17</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
        <span class="site-state-item-count">18</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">7</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/way1989" title="GitHub → https://github.com/way1989" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><a href="https://beian.miit.gov.cn" rel="noopener" target="_blank">粤ICP备20072588号 </a>
      <img src="/images/gongan.png" style="display: inline-block;"><a href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=44030702002235" rel="noopener" target="_blank">粤公网安备 44030702002235号 </a>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Broncho</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/muse.js"></script>
<script src="/js/next-boot.js"></script>



  




  <script src="/js/local-search.js"></script>












  

  

<script>
NexT.utils.loadComments(document.querySelector('#lv-container'), () => {
  window.livereOptions = {
    refer: location.pathname.replace(CONFIG.root, '').replace('index.html', '')
  };
  (function(d, s) {
    var j, e = d.getElementsByTagName(s)[0];
    if (typeof LivereTower === 'function') { return; }
    j = d.createElement(s);
    j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
    j.async = true;
    e.parentNode.insertBefore(j, e);
  })(document, 'script');
});
</script>

</body>
</html>
